package org.dromara.web.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class QRCodeDecoder {

    public static String decodeQRCodeFromURL(String imageUrl) {
        try {
            // 从 URL 下载二维码图片
            URL url = new URL(imageUrl);
            try (InputStream inputStream = url.openStream()) {
                BufferedImage bufferedImage = ImageIO.read(inputStream);
                if (bufferedImage == null) {
                    throw new IllegalArgumentException("无法从提供的 URL 读取图像。");
                }

                // 使用 ZXing 解析二维码
                LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                Map<DecodeHintType, Object> hints = new HashMap<>();
                hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
                Result result = new MultiFormatReader().decode(bitmap, hints);

                // 返回二维码中的文本内容
                return result.getText();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String imageUrl = "https://img.flya.top/img/20241222150009.png";
        String decodedText = decodeQRCodeFromURL(imageUrl);
        if (decodedText != null) {
            System.out.println("二维码内容: " + decodedText);
        } else {
            System.out.println("无法解析二维码。");
        }
    }
}
